﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using ThoughtWorks.QRCode.Codec;
using System.Web;

namespace Heyu.Utility
{
    public class ImageUtility
    {
        public ImageUtility()
        {
        }

        /// <summary>
        /// 将图片转换为二进制流（图片路径）
        /// </summary>
        /// <param name="imagepath"></param>
        /// <returns></returns>
        public static byte[] GetPictureData(string imagepath)
        {
            //根据图片文件的路径使用文件流打开，并保存为byte[]     
            FileStream fs = new FileStream(imagepath, FileMode.Open);
            byte[] bt = new byte[fs.Length];
            fs.Read(bt, 0, bt.Length);
            fs.Close();
            return bt;
        }
        /// <summary>
        /// 将图片转换为二进制流（图片）
        /// </summary>
        /// <param name="imgPhoto"></param>
        /// <returns></returns>
        public static byte[] GetPictureData(Image img)
        {
            //将Image转换成流数据，并保存为byte[]     
            MemoryStream mstream = new MemoryStream();
            img.Save(mstream, ImageFormat.Bmp);
            byte[] bt = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(bt, 0, bt.Length);
            mstream.Close();
            return bt;
        }

        /// <summary>
        /// 将二进制流转为图片
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static Image GetImage(byte[] bt)
        {
            MemoryStream ms = new MemoryStream(bt);
            return Image.FromStream(ms);
        }

        [Obsolete]
        public static Image ReturnPhoto(byte[] bt)
        {
            return GetImage(bt);
        }


        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="bitmap">图片</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="saveName">保存文件名</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="mode">模式</param>
        public static void SaveImage(System.Drawing.Image bitmap, string savePath, string saveName)
        {
            //以jpg格式保存缩略图
            if (!Directory.Exists(savePath)) //如果文件夹不存在则创建
            {
                Directory.CreateDirectory(savePath);
            }
            string savePathName = Path.Combine(savePath, saveName);//文件的保存路径(含文件名)
            bitmap.Save(savePathName, System.Drawing.Imaging.ImageFormat.Jpeg);
            //bitmap.Dispose();
        }
        /// <summary>
        /// 将图片保存到内存中
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static MemoryStream GetMemoryStream(Image image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms;
        }

        /// <summary>
        /// 直接输出图片到页面
        /// </summary>
        /// <param name="page"></param>
        /// <param name="streamByte"></param>
        public static void WritePhoto(System.Web.UI.Page page, byte[] streamByte)
        {
            if (streamByte != null)
            {
                if (streamByte.Length > 0)
                {
                    page.Response.ClearContent();
                    // Response.ContentType 的默认值为默认值为“text/html”  
                    page.Response.ContentType = "image/GIF";
                    //图片输出的类型有: image/GIF  image/JPEG  
                    page.Response.BinaryWrite(streamByte);
                }
                else
                {
                    page.Response.Write("没有图片！");
                }
            }
            else
            {
                page.Response.Write("没有图片！");
            }

        }



        /// <summary>
        /// 保存缩略图
        /// </summary>
        /// <param name="sourcePath">原图路径</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="saveName">保存文件名</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="mode">模式</param>
        public static void SaveThumbnail(string sourcePath, string savePath, string saveName, int width, int height, string mode)
        {
            System.Drawing.Image bitmap = MakeThumbnail(sourcePath, width, height, mode);

            SaveImage(bitmap, savePath, saveName);
        }


        /// <summary>
        /// 根据图片源,生成一个图片缩略图
        /// </summary>
        /// <param name="sourcePath">图片绝对路径</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="mode">模式</param>
        /// <returns></returns>
        public static Image MakeThumbnail(string sourcePath, int width, int height, string mode = "")
        {
            Image originalImage = Image.FromFile(sourcePath);
            return MakeThumbnail(originalImage, width, height, mode);
        }

        /// <summary>
        /// 将图片生成缩略图
        /// </summary>
        /// <param name="originalImage">原始图片</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static Image MakeThumbnail(Image originalImage, int width, int height, string mode = "")
        {
            if (string.IsNullOrEmpty(mode))
            {
                if (width != 0)
                {
                    mode = "W";
                }
                if (height != 0)
                {
                    mode = "H";
                }
                if (width != 0 && height != 0)
                {
                    mode = "Cut";
                }
            }

            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode.Trim().ToLower())
            {
                case "hw"://指定高宽缩放（可能变形）                
                    break;
                case "w"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "h"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "cut"://指定高宽裁减（不变形，按短边裁剪）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "fill"://填充（不变形,按长边裁剪，短边填充）
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    else
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight, PixelFormat.Format24bppRgb);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            try
            {
                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                g.Clear(System.Drawing.Color.White);
                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                    new System.Drawing.Rectangle(x, y, ow, oh),
                    System.Drawing.GraphicsUnit.Pixel);

                return bitmap;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                originalImage.Dispose();
                //bitmap.Dispose();不能销毁bitmap,否则返回数据异常
                g.Dispose();
            }
        }


        /**/
        /// <summary>
        /// 在图片上增加文字水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_sy">生成的带文字水印的图片路径</param>
        protected void AddShuiYinWord(string Path, string Path_sy)
        {
            string addText = "测试水印";
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            System.Drawing.Font f = new System.Drawing.Font("Verdana", 16);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);
            g.DrawString(addText, f, b, 15, 15);
            g.Dispose();
            image.Save(Path_sy);
            image.Dispose();
        }
        /**/
        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
        /// <param name="Path_sypf">水印图片路径</param>
        protected void AddShuiYinPic(string Path, string Path_syp, string Path_sypf)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();
            image.Save(Path_syp);
            image.Dispose();
        }



        /// <summary>
        /// 根据值生成二维码，并保存至本地服务器，返回图片路径
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool creatQrCode(string value, string path = "~/Images/Qrcode.jpg")
        {
            Bitmap bt;
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置编码模式  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //设置编码测量度  
            qrCodeEncoder.QRCodeScale = 2;
            //设置编码版本  
            qrCodeEncoder.QRCodeVersion = 0;
            //设置编码错误纠正  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;


            bt = qrCodeEncoder.Encode(value, Encoding.UTF8);


            //string filename = "Qrcode";
            //string filetype = ".jpg";

            //string wpath = HttpContext.Current.Server.MapPath(path);
            //if (!Directory.Exists(wpath)) //如果文件夹不存在则创建
            //{
            //    Directory.CreateDirectory(wpath);
            //}
            //filename = FileHelper.checkFileExist(path, filename, filetype);


            bt.Save(HttpContext.Current.Server.MapPath(path));
            return true;
        }

        /// <summary>
        /// 将文字转为图片
        /// </summary>
        /// <param name="str"></param>
        public static void StringToImg(ImgAttr attr)
        {
            System.Drawing.Image img = new Bitmap(attr.Width, attr.Height); //创建一个大小为100*100象素的图片
            Graphics g = Graphics.FromImage(img);//从img创建Graphics对象
            g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 100, 100));//填充背景
            g.DrawString(attr.Word, new Font(attr.FontFamily, attr.FontSize), Brushes.White, 10, 10);//在图片上写字
            g.Dispose();//销毁Graphics对象
            g = null;
            img.Save(HttpContext.Current.Server.MapPath("images/test.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);//保存生成的图像文件
            img.Dispose();
            img = null;
        }
    }
}
